#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# motd.sh
# This program calculates a colorized welcome banner with a Star Trek theme.
# -----------------------------------------------------------------------------

FILE="/etc/motd"

# If the file doesn't already exist
if [ ! -f "$FILE" ]; then
	sudo touch "$FILE"
fi

# If the file isn't zero size
if [ -s "$FILE" ]; then
    sudo mv "$FILE" "$FILE".bak
fi

SYSTEM_NAME=`hostname | tr '[:lower:]' '[:upper:]'`
STRING_LENGTH=${#SYSTEM_NAME}
DIFFERENCE=$(( 11 - $STRING_LENGTH ))
DELTA=$(( $DIFFERENCE % 2 ))
DIFFERENCE=$(( $DIFFERENCE - $DELTA ))
INITIAL_SPACE=$(( $DIFFERENCE / 2 ))
END_SPACE=$(( $DIFFERENCE - $INITIAL_SPACE + $DELTA ))

yellow=$(tput setaf 3)
blue=$(tput setaf 4)
white=$(tput setaf 7)
default=$(tput sgr0)
NAME_LINE=`printf '%*s' $INITIAL_SPACE; printf ${yellow}$SYSTEM_NAME${white}; printf '%*s' $END_SPACE;`

sudo chmod o+w $FILE

printf "%s\n" "#!/usr/bin/env bash" >> $FILE
printf "%s\n" "" >> $FILE
printf "%s\n" "printf '${white}\n'" >> $FILE
printf "%s\n" "printf '                         .^.\n'" >> $FILE
printf "%s\n" "printf '                        /   \\\\\n'" >> $FILE
printf "%s\n" "printf '                       /     \\\\\n'" >> $FILE
printf "%s\n" "printf '               ${blue}*******${white}/       \\${blue}*******\n'" >> $FILE
printf "%s\n" "printf '          ***** *****${white}/         \\${blue}***** *****\n'" >> $FILE
printf "%s\n" "printf '      ***** ********${white}/$NAME_LINE\\${blue}******** *****\n'" >> $FILE
printf "%s\n" "printf '     *** **********${white}/             \\${blue}********** ***\n'" >> $FILE
printf "%s\n" "printf '      ***** ******${white}/               \\${blue}****** *****\n'" >> $FILE
printf "%s\n" "printf '          ***** *${white}/        _--_     \\${blue}* *****\n'" >> $FILE
printf "%s\n" "printf '               *${white}/      _-\"${blue}****${white}\"\\\\    \\${blue}*\n'" >> $FILE
printf "%s\n" "printf '               ${white}/    _-\" ${blue}*****   ${white}\"\\\\   \\\\\n'" >> $FILE
printf "%s\n" "printf '               \\\\__-\"              \"\\\\_/\n'" >> $FILE
printf "%s\n" "printf '\n'" >> $FILE
printf "%s\n" "printf '             \\\\\\\\//_ Live long and prosper\n'" >> $FILE
printf "%s\n" "printf '${default}\n'" >> $FILE

sudo chmod o-w $FILE
